package com.lanju.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.User;

@Repository
public class LanJuUserDao {

    @PersistenceContext(unitName = "financialmarketingUnit")
	private EntityManager entityManager;
    
   public  List<User> getUserList(Map<String, Object> map){
    	List<User> list = null;
		try {
			int offset = 0;
			int limit = 0;
			if (!StringUtils.isEmpty(map.get("offset"))
					&& !StringUtils.isEmpty(map.get("limit"))) {
				offset = Integer.parseInt(map.get("offset").toString());
				limit = Integer.parseInt(map.get("limit").toString());
			}
			StringBuffer sql=new StringBuffer();
			sql.append("from User where 1=1");
			if(!StringUtils.isEmpty(map.get("nickName"))){
				sql.append(" and nickName like '%"+map.get("nickName").toString()+"%'");
			}
			if(!StringUtils.isEmpty(map.get("flag"))){
				sql.append(" and flag ="+Integer.valueOf(map.get("flag").toString()));
			}
			Query query=entityManager.createQuery(sql.toString()).setFirstResult(offset).setMaxResults(limit);
			list = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
    }
   
   
   public long getUserListCount(Map<String, Object> map){
   	long count=0;
		try {
			int offset = 0;
			int limit = 0;
			if (!StringUtils.isEmpty(map.get("offset"))
					&& !StringUtils.isEmpty(map.get("limit"))) {
				offset = Integer.parseInt(map.get("offset").toString());
				limit = Integer.parseInt(map.get("limit").toString());
			}
			StringBuffer sql=new StringBuffer();
			sql.append("select count(*) from User where 1=1");
			if(!StringUtils.isEmpty(map.get("nickName"))){
				sql.append(" and nickName like '%"+map.get("nickName").toString()+"%'");
			}
			if(!StringUtils.isEmpty(map.get("flag"))){
				sql.append(" and flag ="+Integer.valueOf(map.get("flag").toString()));
			}
			Query query=entityManager.createQuery(sql.toString());
			count = (long) query.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
   }
}
